package com.servlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
public class Server {
    List<Server_listen>list=new ArrayList<>();

    public List<Server_listen> getList() {
        return list;
    }

    public void setList(List<Server_listen> list) {
        this.list = list;
    }
    @Autowired
    Getpoint getpoint;
    ServerSocket serverSocket;
    public  void beginservlet(){
        try {
            System.out.println("Socket服务器开始运行...");
            serverSocket = new ServerSocket(8800);
            while (true){
                Server_listen server_listen=
                        new Server_listen(getpoint,
                                serverSocket.accept());
                Thread thread=new Thread(server_listen);
                list.add(server_listen);
                thread.start();
            }
        }catch (Exception e){
            System.out.println("已绑定");
        }
    }
    public void closeservlet(){
        try {
            for (int i=0;i<list.size();i++) {
                list.get(i).getSocket().close();
            }
            list=new ArrayList<>();
            serverSocket.close();
        } catch (IOException e) {
            System.out.println("关闭连接");
        }
        System.out.println("关闭");
    }
}
class Server_listen implements Runnable{
    Getpoint getpoint;
    private final Socket socket;
    public Socket getSocket() {
        return socket;
    }
    public Server_listen(Getpoint getpoint, Socket socket) {
        this.getpoint = getpoint;
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8);
            BufferedReader in = new BufferedReader(inputStreamReader);
            while (true) {
                //等待客户端socket的不为空输入流
                String str = in.readLine();
                if (str == null) {
                    break;
                }
                getpoint.getvalue(str,
                        String.valueOf(socket.getInetAddress()));
            }
        }catch (Exception e){
        }finally {
            System.out.println(socket.getInetAddress()+"已关闭");
            try{
                socket.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
